package com.fjp.heartguard.ui.report

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fjp.heartguard.R
import com.fjp.heartguard.app.App
import com.fjp.heartguard.app.Constants
import com.fjp.heartguard.app.base.BaseActivity
import com.fjp.heartguard.app.data.bean.GroupQuestionType
import com.fjp.heartguard.app.data.bean.OlderInfo
import com.fjp.heartguard.app.data.bean.ReportsDetail
import com.fjp.heartguard.app.data.bean.Select
import com.fjp.heartguard.app.ext.init
import com.fjp.heartguard.app.ext.showToast
import com.fjp.heartguard.databinding.ActivityReportDetailBinding
import com.fjp.heartguard.ui.question.RecordActivity
import com.fjp.heartguard.ui.report.adapter.ReportDetailAdapter
import com.fjp.heartguard.viewmodel.ReportDetailViewModel
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.ext.parseState

class ReportDetailActivity : BaseActivity<ReportDetailViewModel, ActivityReportDetailBinding>() {
    lateinit var reportAdapter: ReportDetailAdapter
    lateinit var mReportsDetail: ReportsDetail
    var id: Int = 0
    private var olderId = -1
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.viewModel = mViewModel
        mDatabind.click = ClickProxy()
        mViewModel.title.set("测评结果")
        findViewById<ImageView>(R.id.rightIv).setOnClickListener {
            if (olderId != -1) {
                val intent = Intent(this@ReportDetailActivity, HistoryReportActivity::class.java)
                intent.putExtra(Constants.Intent_OLDER_ID, olderId)
                startActivityForResult(intent, 200)
            }
        }
        reportAdapter = ReportDetailAdapter(mutableListOf(), {})

        mDatabind.recyclerView.init(LinearLayoutManager(this, RecyclerView.VERTICAL, false), reportAdapter)
        val olderInfo = intent.getParcelableExtra<OlderInfo>(Constants.Intent_OLDER)
        if (olderInfo != null) {
            mDatabind.userInfoCl.visibility = View.VISIBLE
            initData(ReportsDetail(olderInfo, null))
            mDatabind.scrollView.scrollTo(0, 0)
        } else {
            mViewModel.showRightImage.set(true)
            id = intent.getIntExtra(Constants.INTENT_REPORT_ID, 0)
            olderId = intent.getIntExtra(Constants.Intent_OLDER_ID, -1)
            mViewModel.getQuestionnaireInfo(id)
        }


    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.reportsDetail.observe(this) {
            parseState(it, {
                mDatabind.userInfoCl.visibility = View.VISIBLE
                initData(it)
                mDatabind.scrollView.scrollTo(0, 0)
            }, {}, {
                dismissLoading()
            })
        }
    }

    private fun initData(reportsDetail: ReportsDetail) {

        this.mReportsDetail = reportsDetail
        mDatabind.ageValueTv.text = reportsDetail.quest.age.toString()
        mDatabind.nameTv.text = reportsDetail.quest.name
        mDatabind.sexValueTv.text = reportsDetail.quest.sex
        mDatabind.addressValueTv.text = reportsDetail.quest.address
        mDatabind.timeTv.text = "测评时间：${reportsDetail.quest.created_at!!.split(" ")[0]}"
        if (reportsDetail.quest.sex == "男") {
            mDatabind.avatarIv.setBackgroundResource(R.drawable.avatarman)
        } else {
            mDatabind.avatarIv.setBackgroundResource(R.drawable.avatar_woman)
        }
        if (reportsDetail.quest == null || reportsDetail.quest.questionnaire == null || reportsDetail.quest.questionnaire.size == 0) {
            return
        }
        mDatabind.compareWarningTitle.visibility = View.VISIBLE
        mDatabind.compareWarning1LL.visibility = View.VISIBLE
        mDatabind.compareWarning2LL.visibility = View.VISIBLE
        mDatabind.compareWarning3LL.visibility = View.VISIBLE
        mDatabind.compareWarning4LL.visibility = View.VISIBLE
        reportAdapter.addData(reportsDetail.quest.questionnaire.filter { it.result?.length != 0 && it.is_show })
        reportAdapter.notifyDataSetChanged()


        val nutritional = reportsDetail.quest.questionnaire.filter { it.type == GroupQuestionType.NUTRITIONAL_STATUS.value }
        var yylevel = 0//营养等级
        if (nutritional.size > 0) {

            if (nutritional[0].score >= 4) {//高于4分营养不良高风险
                yylevel = 0
                mDatabind.comparewarning1DesTv.text = "营养不良高风险"
            } else if (nutritional[0].score >= 2) {
                mDatabind.comparewarning1DesTv.text = "存在营养不良"
                yylevel = 1

            } else {
                yylevel = 2
                mDatabind.comparewarning1DesTv.text = "无"
                mDatabind.comparewarning1DesTv.setTextColor(resources.getColor(R.color.black_25))
            }
        }

        val depressed = reportsDetail.quest.questionnaire.filter { it.type == GroupQuestionType.DEPRESSED.value }
        var yiyulevel = 0//抑郁等级
        if (depressed[0].score > 3) {//高于3分存在抑郁
            yiyulevel = 0
            mDatabind.comparewarning2DesTv.text = "存在抑郁风险"
        } else {
            yiyulevel = 1
            mDatabind.comparewarning2DesTv.text = "无"
            mDatabind.comparewarning2DesTv.setTextColor(resources.getColor(R.color.black_25))
        }
        //跌到高风险过去3个月内跌倒2次及以上，或过去3个月内跌倒1次且有高风险因素（走路不稳等）且未采取防跌倒措施
        // 中度风险过去3个月内跌倒1次，或有高风险因素且未采取防跌倒措施
        val takeCareof = reportsDetail.quest.questionnaire.filter { it.type == GroupQuestionType.TAKE_CARE_OF.value }
        if ((takeCareof[0].question[0].select[0].value.length > 0 && takeCareof[0].question[0].select[0].value.toIntOrNull() != null && takeCareof[0].question[0].select[0].value.toInt() >= 2) || (takeCareof[0].question[0].select[0].value.toIntOrNull() != null && takeCareof[0].question[0].select[0].value.toInt() >= 1 && takeCareof[0].question[1].select[0].is_selected == 1 && takeCareof[0].question[2].select[1].is_selected == 1)) { //高风险
            mDatabind.compareWarning3DesTv.text = "高风险"
        } else if ((takeCareof[0].question[0].select[0].value.toIntOrNull() != null && takeCareof[0].question[0].select[0].value.toInt() == 1) || takeCareof[0].question[1].select[0].is_selected == 1) {//中度风险
            mDatabind.compareWarning3DesTv.text = "中度风险"
        } else if (mDatabind.compareWarning3DesTv.text.length == 0) {
            mDatabind.compareWarning3DesTv.text = "无"
            mDatabind.compareWarning3DesTv.setTextColor(resources.getColor(R.color.black_25))
        }
//        疼痛状况预警：红色预警（需立即关注）：疼痛强度≥7分，或疼痛强度≥5分且未进行任何疼痛管理
//        黄色预警（需要关注）：疼痛强度4-6分，或疼痛强度2-3分但未进行疼痛管理，或存在多处（≥3处）疼痛
        val painIntensity = takeCareof[2].question.filter { it.title.contains("疼痛强度") }
        val painManager = takeCareof[2].question.filter { it.title.contains("是否接受疼痛管理") }
        val painPoint = takeCareof[2].question.filter { it.title.contains("疼痛部位") }
        var painResult: List<Select>? = null
        if (painPoint != null && painPoint.size > 0) {
            painResult = painPoint[0].select.filter { it.is_selected == 1 }
        }
        var tengtonglevel = 2

        if ((painIntensity != null && painIntensity.size > 0 && painIntensity[0].select[0].value.toIntOrNull() != null && painIntensity[0].select[0].value.toInt() >= 7) || (painManager != null && painManager.size > 0 && painManager[0].select[1].is_selected == 1 && painIntensity[0].select[0].value.toInt() >= 5)) {//红色预警（需立即关注）
            mDatabind.compareWarning4DesTv.text = "红色预警（需立即关注）"
            tengtonglevel = 0
        } else if ((painIntensity != null && painIntensity.size > 0 && painIntensity[0].select[0].value.toIntOrNull() != null && painIntensity[0].select[0].value.toInt() >= 4) || ((painIntensity != null && painIntensity.size > 0 && painIntensity[0].select[0].value.toIntOrNull() != null && painIntensity[0].select[0].value.toInt() >= 2) && (painManager != null && painManager.size > 0 && painManager[0].select[1].is_selected == 1)) || (painResult != null && painResult.size >= 3)) {//黄色预警需关注
            mDatabind.compareWarning4DesTv.text = "黄色预警（需要关注）"
            tengtonglevel = 1
        }

        if (mDatabind.compareWarning4DesTv.text.length == 0) {
            mDatabind.compareWarning4DesTv.text = "无"
            mDatabind.compareWarning4DesTv.setTextColor(resources.getColor(R.color.black_25))
        }
        if (mDatabind.comparewarning1DesTv.text == "无") {
            mDatabind.compareWarning1LL.visibility = View.GONE
        }
        if (mDatabind.comparewarning2DesTv.text == "无") {
            mDatabind.compareWarning2LL.visibility = View.GONE
        }
        if (mDatabind.compareWarning3DesTv.text == "无") {
            mDatabind.compareWarning3LL.visibility = View.GONE
        }
        if (mDatabind.compareWarning4DesTv.text == "无") {
            mDatabind.compareWarning4LL.visibility = View.GONE
        }

        if (reportsDetail.pre_quest != null && reportsDetail.pre_quest!!.questionnaire != null && reportsDetail.pre_quest!!.questionnaire.size > 0) {
            mDatabind.compare1LL.visibility = View.VISIBLE
            mDatabind.compare2LL.visibility = View.VISIBLE
            mDatabind.compare3LL.visibility = View.VISIBLE
            mDatabind.compare4LL.visibility = View.VISIBLE
            val prenutritional = reportsDetail.pre_quest!!.questionnaire.filter { it.type == GroupQuestionType.NUTRITIONAL_STATUS.value }
            var preyylevel = 0
            if (prenutritional[0].score >= 4) {//高于4分营养不良高风险
                preyylevel = 0
            } else if (prenutritional[0].score >= 2) {
                preyylevel = 1

            } else {
                preyylevel = 2
            }

            if (prenutritional[0].score == nutritional[0].score) {
                mDatabind.scoreDes1Tv.text = "与上次持平"
                mDatabind.levelDes1Tv.text = "风险等级不变"
                mDatabind.scoreArrow1Iv.setBackgroundResource(R.drawable.warning_flat)
                mDatabind.levelArrow1Iv.setBackgroundResource(R.drawable.warning_flat)
            } else if (prenutritional[0].score > nutritional[0].score) {
                mDatabind.scoreDes1Tv.text = "与上次相比低${prenutritional[0].score - nutritional[0].score} 分"
                mDatabind.scoreArrow1Iv.setBackgroundResource(R.drawable.warning_down)
                if (preyylevel == yylevel) {
                    mDatabind.levelDes1Tv.text = "风险等级不变"
                    mDatabind.levelArrow1Iv.setBackgroundResource(R.drawable.warning_flat)
                } else {
                    mDatabind.levelDes1Tv.text = "风险等级降低"
                    mDatabind.levelArrow1Iv.setBackgroundResource(R.drawable.warning_down)
                }
            } else {
                mDatabind.scoreDes1Tv.text = "与上次相比高${nutritional[0].score - prenutritional[0].score} 分"
                mDatabind.scoreArrow1Iv.setBackgroundResource(R.drawable.warning_up)
                if (preyylevel == yylevel) {
                    mDatabind.levelDes1Tv.text = "风险等级不变"
                    mDatabind.levelArrow1Iv.setBackgroundResource(R.drawable.warning_flat)
                } else {
                    mDatabind.levelDes1Tv.text = "风险等级升高"
                    mDatabind.levelArrow1Iv.setBackgroundResource(R.drawable.warning_up)
                }
            }

            val predepressed = reportsDetail.pre_quest!!.questionnaire.filter { it.type == GroupQuestionType.DEPRESSED.value }
            var preyiyulevel = 0//抑郁等级
            if (predepressed[0].score > 3) {//高于3分存在抑郁
                preyiyulevel = 0
            } else {
                preyiyulevel = 1
            }

            if (predepressed[0].score == depressed[0].score) {
                mDatabind.scoreDes2Tv.text = "与上次持平"
                mDatabind.levelDes2Tv.text = "风险等级不变"
                mDatabind.scoreArrow2Iv.setBackgroundResource(R.drawable.warning_flat)
                mDatabind.levelArrow2Iv.setBackgroundResource(R.drawable.warning_flat)
            } else if (predepressed[0].score > depressed[0].score) {
                mDatabind.scoreDes2Tv.text = "与上次相比低${predepressed[0].score - depressed[0].score} 分"
                mDatabind.scoreArrow2Iv.setBackgroundResource(R.drawable.warning_down)
                if (preyiyulevel == yiyulevel) {
                    mDatabind.levelDes2Tv.text = "风险等级不变"
                    mDatabind.levelArrow2Iv.setBackgroundResource(R.drawable.warning_flat)
                } else {
                    mDatabind.levelDes2Tv.text = "风险等级降低"
                    mDatabind.levelArrow2Iv.setBackgroundResource(R.drawable.warning_down)
                }
            } else {
                mDatabind.scoreDes2Tv.text = "与上次相比高${depressed[0].score - predepressed[0].score} 分"
                mDatabind.scoreArrow2Iv.setBackgroundResource(R.drawable.warning_up)
                if (preyiyulevel == yiyulevel) {
                    mDatabind.levelDes2Tv.text = "风险等级不变"
                    mDatabind.levelArrow2Iv.setBackgroundResource(R.drawable.warning_flat)
                } else {
                    mDatabind.levelDes2Tv.text = "风险等级升高"
                    mDatabind.levelArrow2Iv.setBackgroundResource(R.drawable.warning_up)
                }
            }


            //跌到高风险过去3个月内跌倒2次及以上，或过去3个月内跌倒1次且有高风险因素（走路不稳等）且未采取防跌倒措施
            // 中度风险过去3个月内跌倒1次，或有高风险因素且未采取防跌倒措施
            var pre3Des = "无"
            val pretakeCareof = reportsDetail.pre_quest!!.questionnaire.filter { it.type == GroupQuestionType.TAKE_CARE_OF.value }
            if ((pretakeCareof[0].question[0].select[0].value.length > 0 && pretakeCareof[0].question[0].select[0].value.toIntOrNull() != null && pretakeCareof[0].question[0].select[0].value.toInt() >= 2) || (pretakeCareof[0].question[0].select[0].value.toIntOrNull() != null && pretakeCareof[0].question[0].select[0].value.toInt() >= 1 && pretakeCareof[0].question[1].select[0].is_selected == 1 && pretakeCareof[0].question[2].select[1].is_selected == 1)) { //高风险
                pre3Des = "高风险"
            } else if ((pretakeCareof[0].question[0].select[0].value.toIntOrNull() != null && pretakeCareof[0].question[0].select[0].value.toInt() == 1) || pretakeCareof[0].question[1].select[0].is_selected == 1) {//中度风险
                pre3Des = "中度风险"
            } else if (mDatabind.compareWarning3DesTv.text == "无") {
                mDatabind.compareWarning3DesTv.setTextColor(resources.getColor(R.color.black_25))
            }


            mDatabind.scoreDes3Tv.text = "上一次等级：${pre3Des}"
            if (mDatabind.compareWarning3DesTv.text == pre3Des) {
                mDatabind.levelDes3Tv.text = "风险等级不变"
                mDatabind.levelArrow3Iv.setBackgroundResource(R.drawable.warning_flat)
            } else {
                if ((mDatabind.compareWarning3DesTv.text == "中度风险" && pre3Des == "高风险") || (mDatabind.compareWarning3DesTv.text == "无" && pre3Des == "中度风险")) {
                    mDatabind.levelDes3Tv.text = "风险等级降低"
                    mDatabind.levelArrow3Iv.setBackgroundResource(R.drawable.warning_down)
                } else {
                    mDatabind.levelDes3Tv.text = "风险等级升高"
                    mDatabind.levelArrow3Iv.setBackgroundResource(R.drawable.warning_up)
                }
            }


//        疼痛状况预警：红色预警（需立即关注）：疼痛强度≥7分，或疼痛强度≥5分且未进行任何疼痛管理
//        黄色预警（需要关注）：疼痛强度4-6分，或疼痛强度2-3分但未进行疼痛管理，或存在多处（≥3处）疼痛
            val prepainIntensity = pretakeCareof[2].question.filter { it.title.contains("疼痛强度") }
            val prepainManager = pretakeCareof[2].question.filter { it.title.contains("是否接受疼痛管理") }
            val prepainPoint = pretakeCareof[2].question.filter { it.title.contains("疼痛部位") }
            var prepainResult: List<Select>? = null
            var pretengtonglevel = 2
            if (prepainPoint != null && prepainPoint.size > 0) {
                prepainResult = prepainPoint[0].select.filter { it.is_selected == 1 }
            }

            var pre4Des = "无风险"
            if ((prepainIntensity != null && prepainIntensity.size > 0 && prepainIntensity[0].select[0].value.toIntOrNull() != null && prepainIntensity[0].select[0].value.toInt() >= 7) || (prepainManager != null && prepainManager.size > 0 && prepainManager[0].select[1].is_selected == 1 && prepainIntensity != null && prepainIntensity.size > 0 && prepainIntensity[0].select[0].value.toIntOrNull() != null && prepainIntensity[0].select[0].value.toInt() >= 5)) {//红色预警（需立即关注）
                pre4Des = "红色预警"
                pretengtonglevel = 0
            } else if ((prepainIntensity != null && prepainIntensity.size > 0 && prepainIntensity[0].select[0].value.toIntOrNull() != null && prepainIntensity[0].select[0].value.toInt() >= 4) || ((prepainIntensity != null && prepainIntensity.size > 0 && prepainIntensity[0].select[0].value.toIntOrNull() != null && prepainIntensity[0].select[0].value.toInt() >= 2) && (prepainManager != null && prepainManager.size > 0 && prepainManager[0].select[1].is_selected == 1)) || (prepainResult != null && prepainResult.size >= 3)) {//黄色预警需关注
                pre4Des = "黄色预警"
                pretengtonglevel = 1
            }

            mDatabind.scoreDes4Tv.text = "上一次等级：${pre4Des}"
            if (pretengtonglevel == tengtonglevel) {
                mDatabind.levelDes4Tv.text = "风险等级不变"
                mDatabind.levelArrow4Iv.setBackgroundResource(R.drawable.warning_flat)
            } else {
                if (pretengtonglevel < tengtonglevel) {
                    mDatabind.levelDes4Tv.text = "风险等级降低"
                    mDatabind.levelArrow4Iv.setBackgroundResource(R.drawable.warning_down)
                } else {
                    mDatabind.levelDes4Tv.text = "风险等级升高"
                    mDatabind.levelArrow4Iv.setBackgroundResource(R.drawable.warning_up)
                }
            }


        }

    }

    inner class ClickProxy {
        fun clickReTest() {
            if (this@ReportDetailActivity::mReportsDetail.isInitialized) {
                if (App.accountState.is_self_edit == 0) {//当前账号已被禁用
                    appContext.showToast("请先完善个人信息！")
                    return
                }
                if (App.accountState.status == 2) {//当前账号已被禁用
                    appContext.showToast("当前账号已被禁用无法测评！")
                    return
                }
                val intent = Intent(this@ReportDetailActivity, RecordActivity::class.java)
                intent.putExtra(Constants.Intent_REPORT, mReportsDetail.quest)
                startActivity(intent)
                finish()
            }

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            val id = data?.getIntExtra(Constants.INTENT_REPORT_ID, 0)
            id?.let {
                mViewModel.getQuestionnaireInfo(it)
            }

        }
    }
}